package com.LeeCode;

/**
 * 最长同值路径
 */

public class Code687 {
    public static void main(String[] args) {
        Integer[] arr = {5, 5, 5, 4, null, null, 5};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code687().longestUnivaluePath(root));
    }

    private int ans = 0;

    public int longestUnivaluePath(TreeNode root) {
        if (root == null) return 0;
        dfs(root, root.val);
        return ans;
    }

    private int dfs(TreeNode root, int num) {
        if (root == null) return 0;
        int left = dfs(root.left, root.val);
        int right = dfs(root.right, root.val);
        ans = Math.max(ans, left + right);
        if (root.val != num) {
            return 0;
        } else {
            return Math.max(left, right) + 1;
        }
    }
}
